package com.javaspeak.designpatterns.go4.behavioural.command;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * This Command class reads in a map of request attributes from the request and
 * sorts them by the attribute values and returns them in a new map which is
 * passed to the handleResponse(..) method.
 *
 * @author John Dickerson
 */
public class SortCommand implements Command {

    /**
     * A comparator that sorts the keys of the map according the values
     * associated with each key
     *
     * @author John Dickerson
     */
    class ValueComparator implements Comparator<String> {

        private Map<String,String> base;

        public ValueComparator( Map<String,String> base ) {

            this.base = base;
        }

        public int compare(String a, String b) {

          return base.get( a ).compareTo( base.get( b ) );
        }
    }


    /* (non-Javadoc)
     * @see com.javaspeak.designpatterns.go4.behavioural.command.Command#
     *      execute(com.javaspeak.designpatterns.go4.behavioural.command.
     *          Request, com.javaspeak.designpatterns.go4.behavioural.
     *              command.Response)
     */
    @Override
    public void execute(Request request, Response response) {

        Map<String,String> requestAttributes = request.getRequestAttributes();

        Map<String,String> responseAttributes =
            new TreeMap<String,String>(
                    new ValueComparator( requestAttributes ) );

        responseAttributes.putAll( requestAttributes );

        response.handleResponse( responseAttributes );
    }
}
